import 'dart:convert';

import 'package:palmf_hid/common/entities/user_entity.dart';
import 'package:get/get.dart';
import 'package:palmf_hid/common/services/services.dart';
import 'package:palmf_hid/common/utils/utils.dart';
import 'package:palmf_hid/common/values/storage.dart';

class UserStore extends GetxController {
  static UserStore get to => Get.find();
  final _isRememberMe = true.obs;

  // 是否登录
  final _isLogin = false.obs;

  // 令牌 token
  String _passWord = "";
  String _userName = "";

  // 用户 profile

  get isRememberMe => _isRememberMe.value;

  set isRememberMe(value) => _isRememberMe.value = value;

  bool get isLogin => _isLogin.value;


  String get passWord => _passWord;

  String get userName => _userName;

  @override
  void onInit() {
    super.onInit();
    var profileOffline = StorageService.to.getString(USER_NAME);
    if (profileOffline.isNotEmpty) {
      _isLogin.value = true;
    } else {
      _isLogin.value = false;
    }
    if (StorageService.to.containsKey(REMEMBER_ME)) {
      isRememberMe = StorageService.to.getBool(REMEMBER_ME);
    }
    _passWord = StorageService.to.getString(USER_PSW);
    _userName = StorageService.to.getString(USER_NAME);
  }

  saveRememberMe(bool remember) {
    isRememberMe = remember;
    StorageService.to.setBool(REMEMBER_ME, remember);
    MyLogUtil().i(StorageService.to.getBool(REMEMBER_ME));
  }

  savePassWord(String psw) {
    _passWord = psw;
    StorageService.to.setString(USER_PSW, psw);
    _isLogin.value = true;
  }

  saveUserName(String userName) {
    _userName = userName;
    StorageService.to.setString(USER_NAME, userName);
  }

  // 注销
  Future<void> onLogout() async {
    _isLogin.value = false;
    StorageService.to.remove(STORAGE_USER_PROFILE_KEY);
    if (!isRememberMe) {
      StorageService.to.remove(USER_PSW);
      StorageService.to.remove(USER_NAME);
    }

    StorageService.to.clear();
    if (isRememberMe) {
      savePassWord(passWord);
      saveUserName(userName);
      saveRememberMe(true);
    } else {
      _passWord = "";
      _userName = "";
    }
  }
}
